package com.servlet;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

/**
 * Created by xiao zeng on 2017/6/28.
 */
@WebServlet("/commupload.action")//comms上传
public class CommUpload extends HttpServlet {

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        DiskFileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload up = new ServletFileUpload(factory);
        try {
            List<FileItem> list = up.parseRequest(req);
            for (FileItem f : list){
                if (f.isFormField()){

                    String user = f.getString("utf-8");
                    String username = f.getFieldName();
                    System.out.println(user+"......."+username);
                }
                String name = f.getName();
                if (null!=name){
                    String path = req.getServletContext().getRealPath("/upload/comm");
                    File fi  = new File(path);
                    if (!fi.exists()){
                        fi.mkdirs();
                    }
                    String ext = name.substring(name.lastIndexOf(".")).toLowerCase();
                    System.out.println(ext);
                    f.write(new File(path+"/"+name));
                }
            }
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
